import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author zyj
 * @date 2022年06月13日 9:33
 */
public class Demo {
    public static void main(String[] args) {
        //传一个对象能实现一个查询语句
        //select * from 表名 where 条件
        //是根据类上面的注解所对应的value值类设置
        //字段 -- 类的属性来设置
        //需要两个注解类 表的注解 -- 查询的表
        //字段的注解  -- 你查询的时候的条件 -- 哪些字段来设置的
        Student s = new Student(1, "张三");

        //生成sql select * from student where id = "1" and stu_name = "张三"

        String sql = query(s);
        System.out.println(sql);


    }

    private static String query(Student s) {
        Class clazz = s.getClass();

        StringBuilder sb = new StringBuilder("select * from ");
        //先判断该类上面是否有这个注解

        boolean flag = clazz.isAnnotationPresent(Table.class);
        if (!flag) {
            return null;
        }
        Table table = (Table) clazz.getDeclaredAnnotation(Table.class);
        String tableName = table.value();
        sb.append(tableName).append(" where 1=1 ");

        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            boolean f1 = f.isAnnotationPresent(Column.class);
            if (f1) {
                Column column = f.getDeclaredAnnotation(Column.class);
                String columnName = column.value();


                String fieldName = f.getName();
                String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    Method m = clazz.getMethod(methodName);
                    Object obj = m.invoke(s);
                    sb.append("and ").append(columnName).append(" = \"");
                    sb.append(obj).append("\" ");

                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
        return sb.toString().substring(0, sb.length() - 1);
    }
}
